Completed
Push — master ( a1f32a...930790 )
by greg
01:45
created

template.js ➔ addOrder   A

Complexity

Conditions 3
Paths 7

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
nc 7
dl 0
loc 21
rs 9.3142
c 1
b 0
f 0
nop 1

1 Function

Rating   Name   Duplication   Size   Complexity  
B template.js ➔ ... ➔ ??? 0 12 6
1
import fse from 'fs-extra'
2
import {Promise} from 'bluebird'
3
import path from 'path'
4
import {
5
  config,
6
  coreUtils,
7
  cmsData,
8
  abeExtend
9
} from '../../'
10
11
export function getTemplatesAndPartials(templatesPath) {
12
  var p = new Promise((resolve) => {
13
    const extension = '.' + config.files.templates.extension
14
    return coreUtils.file.getFilesAsync(templatesPath, true, extension)
15
      .then(function(files){
16
        return resolve(files)
17
      })
18
  })
19
20
  return p
21
}
22
23
export function addOrder(text) {
24
  var regAbe = /{{abe[\S\s].*?key=['|"]([\S\s].*?['|"| ]}})/g
25
  var matches = text.match(regAbe)
26
  var order = 0
27
  
28
  if(typeof matches !== 'undefined' && matches !== null){
29
    Array.prototype.forEach.call(matches, (match) => {
30
      if(typeof match !== 'undefined' && match !== null) {
31
        
32
        var orderAttr = cmsData.regex.getAttr(match, 'order')
33
34
        if(typeof orderAttr === 'undefined' || orderAttr === null || orderAttr === '') {
35
          var matchOrder = match.replace(/\}\}$/, ` order='${order}'}}`)
36
          text = text.replace(match, matchOrder)
37
        }
38
        order++
39
      }
40
    })
41
  }
42
  return text
43
}
44
45
export function getAbeImport(text) {
46
  var partials = []
47
  let listReg = /({{abe.*?type=[\'|\"]import.*?}})/g
48
  var match
49
  while (match = listReg.exec(text)) {
50
    partials.push(match[0])
51
  }
52
53
  return partials
54
}
55
56
export function includePartials(text) {
57
  var abeImports = getAbeImport(text)
58
59
  Array.prototype.forEach.call(abeImports, (abeImport) => {
60
    var obj = cmsData.attributes.getAll(abeImport, {})
61
62
    var file = obj.file
63
    var partial = ''
64
    file = path.join(config.root, config.partials, file)
65
    if(coreUtils.file.exist(file)) {
66
      partial = includePartials(fse.readFileSync(file, 'utf8'))
67
    }
68
    text = text.replace(cmsData.regex.escapeTextToRegex(abeImport, 'g'), partial)
69
  })
70
71
  return text
72
}
73
74
function translate(text) {
75
  var importReg = /({{abe.*type=[\'|\"]translate.*}})/g
76
77
  var matches = text.match(importReg)
78
  
79
  if(typeof matches !== 'undefined' && matches !== null) {
80
    Array.prototype.forEach.call(matches, (match) => {
81
      var splitedMatches = match.split('{{abe ')
82
83
      Array.prototype.forEach.call(splitedMatches, (splitedMatch) => {
84
        var currentMatch = `{{abe ${splitedMatch}`
85
        if(/({{abe.*type=[\'|\"]translate.*}})/.test(currentMatch)) {
86
          var locale = cmsData.regex.getAttr(currentMatch, 'locale')
87
          var source = cmsData.regex.getAttr(currentMatch, 'source')
88
89
          if (locale.indexOf('{{') === -1) {
90
            locale = `'${locale}'`
91
          }else {
92
            locale = locale.replace(/\{\{(.*?)\}\}/, '$1')
93
          }
94
95
          if (source.indexOf('{{') === -1) {
96
            source = `'${source.replace(/'/g, '\\\'')}'`
97
          }else {
98
            source = source.replace(/\{\{(.*?)\}\}/, '$1')
99
          }
100
101
          // var replace = `{{{i18nAbe ${locale} ${source}}}}`
102
          var replace = currentMatch.replace('{{abe', '{{i18nAbe')
103
          replace = replace.replace(/locale=['|"].*?['|"]/, locale)
104
          replace = replace.replace(/source=['|"].*?['|"]/, source)
105
          replace = replace.replace(/{{i18nAbe.*?}}/, `{{{i18nAbe ${locale} ${source}}}}`)
106
107
          text = text.replace(cmsData.regex.escapeTextToRegex(currentMatch, 'g'), replace)
108
        }
109
      })
110
    })
111
  }
112
113
  return text
114
}
115
116
export function getTemplate (file) {
117
  var text = ''
118
119
  // HOOKS beforeGetTemplate
120
  file = abeExtend.hooks.instance.trigger('beforeGetTemplate', file)
121
122
  file = file.replace(path.join(config.root, config.templates.url), '')
123
  file = file.replace(config.root, '')
124
  if (file.indexOf('.') > -1) {
125
    file = file.replace(/\..+$/, '')
126
  }
127
  file = path.join(config.root, config.templates.url, file + '.' + config.files.templates.extension)
128
  if(coreUtils.file.exist(file)) {
129
    text = fse.readFileSync(file, 'utf8')
130
    text = includePartials(text)
131
    text = translate(text)
132
    text = addOrder(text)
133
  }else {
134
    text = `[ ERROR ] template ${file + '.' + config.files.templates.extension} doesn't exist anymore`
135
  }
136
137
  // HOOKS afterGetTemplate
138
  text = abeExtend.hooks.instance.trigger('afterGetTemplate', text)
139
140
  return text
141
}
142
143
export function getVariablesInWhere(where) {
144
  var ar = []
145
146
  if(where.left.column.indexOf('{{') > -1) {
147
    ar.push(where.left.column.replace(/\{\{(.*?)\}\}/, '$1'))
148
  }
149
  else{
150
    ar.push(where.left.column)
151
  }
152
153
  if (where.right.value) {
154
    if (typeof where.right.value === 'string') {
155
      if(where.right.value && where.right.value.indexOf('{{') > -1) {
156
        ar.push(where.right.value.replace(/\{\{(.*?)\}\}/, '$1'))
157
      }
158
    }else {
159
      where.right.value.forEach(function (value) {
160
        if(value.column.indexOf('{{') > -1) {
161
          ar.push(value.column.replace(/\{\{(.*?)\}\}/, '$1'))
162
        }
163
      })
164
    }
165
  }
166
167
  if(where.right.column && where.right.column.indexOf('{{') > -1) {
168
    ar.push(where.right.column.replace(/\{\{(.*?)\}\}/, '$1'))
169
  }
170
171
  return ar
172
}
173
174
/**
175
 * Get columns and where.left ids of a select statement
176
 *
177
 * select title, image from ../ where template=""
178
 *
179
 * return [title, image, template]
180
 * 
181
 * @param  {Array} templatesList ["article.html", "other.html"]
0 ignored issues
show
Documentation introduced by
The parameter templatesList does not exist. Did you maybe forget to remove this comment?
Loading history...
182
 * @return {Promise}
183
 */
184
export function recurseWhereVariables (where) {
185
  var ar = []
0 ignored issues
show
Unused Code introduced by
The assignment to variable ar seems to be never used. Consider removing it.
Loading history...
186
  var arLeft
187
  var arRight
188
  switch(where.operator) {
189
  case 'AND':
190
    arLeft = recurseWhereVariables(where.left)
191
    arRight = recurseWhereVariables(where.right)
192
    return arLeft.concat(arRight)
193
    break
0 ignored issues
show
Unused Code introduced by
This break statement is unnecessary and may be removed.
Loading history...
194
  case 'OR':
195
    arLeft = recurseWhereVariables(where.left)
196
    arRight = recurseWhereVariables(where.right)
197
    return arLeft.concat(arRight)
198
    break
0 ignored issues
show
Unused Code introduced by
This break statement is unnecessary and may be removed.
Loading history...
199
  default:
200
    ar = getVariablesInWhere(where)
201
    break
202
  }
203
204
  return ar
205
}
206
207
export function execRequestColumns(tpl) {
208
  var ar = []
209
  var matches = cmsData.regex.getTagAbeTypeRequest(tpl)
210
  Array.prototype.forEach.call(matches, (match) => {
211
    var obj = cmsData.attributes.getAll(match[0], {})
212
    var type = cmsData.sql.getSourceType(obj.sourceString)
213
    switch (type) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
214
    case 'request':
215
      var request = cmsData.sql.handleSqlRequest(obj.sourceString, {})
216
      if(typeof request.columns !== 'undefined' && request.columns !== null) {
217
        Array.prototype.forEach.call(request.columns, (column) => {
218
          ar.push(column)
219
        })
220
      }
221
      if(typeof request.where !== 'undefined' && request.where !== null) {
222
        ar = ar.concat(recurseWhereVariables(request.where))
223
      }
224
    }
225
  })
226
227
  return ar
228
}
229
230
export function findRequestColumns(templatesList) {
231
  var whereKeys = []
232
  var p = new Promise((resolve) => {
233
    Array.prototype.forEach.call(templatesList, (file) => {
234
      var template = fse.readFileSync(file, 'utf8')
235
      whereKeys = whereKeys.concat(execRequestColumns(template))
236
    })
237
    whereKeys = whereKeys.filter(function (item, pos) {return whereKeys.indexOf(item) == pos})
238
    resolve(whereKeys)
239
  })
240
241
  return p
242
}
243
244
export function getSelectTemplateKeys(templatesPath) {
245
  var p = new Promise((resolve, reject) => {
246
    return getTemplatesAndPartials(templatesPath)
247
      .then((templatesList) => {
248
        return findRequestColumns(templatesList)
249
          .then((whereKeys) => {
250
            resolve(whereKeys)
251
          },
252
          (e) => {
253
            console.log('findRequestColumns reject')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
254
            reject(e)
255
          })
256
          .catch((e) => {
257
            console.error('getSelectTemplateKeys', e)
258
            reject()
259
          })
260
      },
261
      () => {
262
        console.log('getTemplateAndPartials reject')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
263
        reject()
264
      })
265
      .catch((e) => {
266
        console.error('getSelectTemplateKeys', e)
267
        reject()
268
      })
269
270
  })
271
272
  return p
273
}
274
275
export function getStructureAndTemplates() {
276
  var site = cmsData.revision.filePathInfos(config.root)
277
  var result = {'structure': [], 'templates': []}
278
279
  const pathStructure = path.join(site.path, config.structure.url)
280
  const pathTemplates = path.join(site.path, config.templates.url)
281
  try {
282
    let directoryStructure = fse.lstatSync(pathStructure)
283
    if (directoryStructure.isDirectory()) {
284
      result.structure = cmsData.file.getFolders(pathStructure, false)
285
    }
286
  } catch (e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
287
  }
288
  try {
289
    let directoryTemplate = fse.lstatSync(pathTemplates)
290
    if (directoryTemplate.isDirectory()) {
291
      let extension = '.' + config.files.templates.extension
292
      let resultTemplates = []
0 ignored issues
show
Unused Code introduced by
The variable resultTemplates seems to be never used. Consider removing it.
Loading history...
293
      let templatePaths = coreUtils.file.getFilesSync(pathTemplates, true, extension)
294
      Array.prototype.forEach.call(templatePaths, (templatePath) => {
295
        let additionalPath = path.dirname(templatePath).replace(pathTemplates,'')
296
        if(additionalPath !== '') additionalPath = additionalPath.substring(1)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
297
        let name = path.join(additionalPath,path.basename(templatePath,extension))
298
        let template = {'path':templatePath, 'cleanPath':templatePath, 'cleanNameNoExt':name}
299
        result.templates.push(template)
300
      })
301
    }
302
  } catch (e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
303
  }
304
305
  return result
306
}